package com.longcai.cm.moudules.system.service.impl;

import com.longcai.cm.moudules.system.domain.SysUsers;
import com.longcai.cm.moudules.system.service.SysUserOnlineService;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author Administrator
 * @Title: SysUserOnlineServiceImpl
 * @ProjectName lc_master
 * @Description: TODO
 * @date 2018/11/2115:24
 */
@Service("SysUserOnlineService")
public class SysUserOnlineServiceImpl implements SysUserOnlineService {
    private final SessionDAO sessionDAO;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    public SysUserOnlineServiceImpl(SessionDAO sessionDAO) {
        this.sessionDAO = sessionDAO;
    }

    @Override
    public List<SysUsers> queryUserOnline() {
        List<SysUsers> list = new ArrayList<>();
        try {
            // 获取在线用户
            Collection<Session> sessions = sessionDAO.getActiveSessions();
            System.out.println("sessions.size()+=" + sessions.size());
            for (Session session : sessions) {
                SysUsers sysUserOnline = new SysUsers();
                if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null) {
                    continue;
                } else {
                    SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
                    SysUsers sysUsers = (SysUsers) principalCollection.getPrimaryPrincipal();
                    sysUserOnline.setUsername(sysUsers.getUsername());
                }
                sysUserOnline.setId(session.getId().toString());
//				sysUserOnline.setHost(session.getHost());
//				sysUserOnline.setStartTimestamp(session.getStartTimestamp());
//				sysUserOnline.setLastAccessTime(session.getLastAccessTime());
//				sysUserOnline.setTimeout(session.getTimeout());
                list.add(sysUserOnline);
            }
        } catch (InvalidSessionException e) {
            e.printStackTrace();
            logger.error("加载在线用户失败", e, getClass());
        }
        return list;
    }

    @Override
    public boolean forceLogout(String id) {
        Session session = sessionDAO.readSession(id);
        session.setTimeout(0);
        return true;
    }
}
